package com.lzw.bluetoothpractice.Utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;

import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;


import com.lzw.bluetoothpractice.Activitys.LoginActivity;
import com.lzw.bluetoothpractice.MyApplication;
import com.lzw.bluetoothpractice.R;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import androidx.annotation.NonNull;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class AppUtil {
    /**
     * 获取软件自身版本号
     *
     * @return 当前应用的版本号
     */
    public static int getVersionCode() {
        int version;
        PackageManager packageManager = MyApplication.getContext().getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(MyApplication.getContext()
                    .getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        version = packInfo.versionCode;
        return version;
    }

    /**
     * 获取软件自身版本号
     *
     * @return 当前应用的版本号
     */
    public static int getselfVersionCode(Context context) {
        String packname = context.getPackageName();
        return getappVersionCode(context, packname);
    }

    /**
     * 获取软件自身版本名
     *
     * @return 当前应用的版本号
     */
    public static String getselfVersionName(Context context) {
        String packname = context.getPackageName();
        return getappVersionName(context, packname);
    }

    public static int getappVersionCode(Context context, String packageName) {
        try {
            return context.getPackageManager().getPackageInfo(packageName, 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getappVersionName(Context context, String packageName) {
        try {
            return context.getPackageManager().getPackageInfo(packageName, 0).versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取APP崩溃异常报告
     *
     * @param ex
     * @return
     */
    public static String getCrashReport(Context context, Throwable ex) {
        PackageInfo pinfo = getPackageInfo(context);
        StringBuffer exceptionStr = new StringBuffer();
        // exceptionStr.append("version: " + pinfo.versionName + "(" +
        // pinfo.versionCode + ")\n");
        exceptionStr.append("android:" + Build.VERSION.RELEASE + "(" + Build.MODEL + ")\n");
        exceptionStr.append("Exception:" + ex.getMessage() + "\n");
        StackTraceElement[] elements = ex.getStackTrace();
        for (int i = 0; i < elements.length; i++) {
            exceptionStr.append(elements[i].toString() + "\n");
        }
        return exceptionStr.toString();
    }

    public static String getPackName() {
        return MyApplication.getContext().getPackageName();
    }

    public static String getAppName() {
        return MyApplication.getContext().getResources().getString(R.string.app_name);
    }

    /**
     * 获取App安装包信息
     *
     * @return
     */
    public static PackageInfo getPackageInfo(Context context) {
        PackageInfo info = null;
        try {
            info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
        }
        if (info == null)
            info = new PackageInfo();
        return info;
    }

    /**
     * 提出APP自己结束进程 ）
     *
     * @return
     */
    public static void exit() {
        killProcess(android.os.Process.myPid());
    }

    /**
     * 根据进程id结束进程
     *
     * @param Processid
     */
    public static void killProcess(int Processid) {
        android.os.Process.killProcess(Processid);
    }

    /**
     * 获取Meta值
     *
     * @param context
     * @param metaKey
     * @return
     */
    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (NameNotFoundException e) {

        }
        return apiKey;
    }

    @SuppressLint("MissingPermission")
    public static String getImei(Context context) {
        // 权限：android:name="android.permission.READ_PHONE_STATE" />
        return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
    }

    // 通过PackageManager的api 查询已经安装的apk
    private List<ResolveInfo> loadApps(Context context) {
        List<ResolveInfo> mApps;
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        mApps = context.getPackageManager().queryIntentActivities(mainIntent, 0);
        return mApps;
    }

    /**
     * 获取SIM卡运营商
     *
     * @param context
     * @return
     */
    public static String getOperators(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String operator = "";
        @SuppressLint("MissingPermission") String IMSI = tm.getSubscriberId();
        if (IMSI == null || IMSI.equals("")) {
            return operator;
        }
        if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {
            operator = "中国移动";
        } else if (IMSI.startsWith("46001")) {
            operator = "中国联通";
        } else if (IMSI.startsWith("46003")) {
            operator = "中国电信";
        }
        return operator;
    }

    /**
     * 手机型号
     *
     * @return
     */
    public static String getPhoneModel() {
        return Build.MODEL;
    }

    /**
     * 系统版本
     *
     * @return
     */
    public static String getSystemVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 是否安装了相关应用
     */
    public static boolean checkHasInstalledApp(@NonNull Context context, String pkgName) {
        PackageManager pm = context.getPackageManager();
        boolean app_installed;
        try {
            pm.getPackageInfo(pkgName, PackageManager.GET_GIDS);
            app_installed = true;
        } catch (NameNotFoundException e) {
            app_installed = false;
        } catch (RuntimeException e) {
            app_installed = false;
        }
        return app_installed;
    }

    /**
     * 获取当前ip地址
     *
     * @param context
     * @return
     */
    public static String getLocalIpAddress(Context context) {
        try {

            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int i = wifiInfo.getIpAddress();
            return int2ip(i);
        } catch (Exception ex) {
            return " 获取IP出错鸟!!!!请保证是WIFI,或者请重新打开网络!\n" + ex.getMessage();
        }
        // return null;
    }

    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt
     * @return
     */
    public static String int2ip(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }

    /**
     * 获取设备编号
     *
     * @return
     */
    public static String getSerialNumber() {

        String serial = null;

        try {

            Class<?> c = Class.forName("android.os.SystemProperties");

            Method get = c.getMethod("get", String.class);

            serial = (String) get.invoke(c, "ro.serialno");

        } catch (Exception e) {

            e.printStackTrace();

        }

        return serial;

    }

    /***获取系统版本***/
    public static String getSystemBuild() {
        String str = "", strCPU = "", cpuAddress = "0000000000000000";
        String strss = "";
        try {
            // 读取CPU信息
            Process pp = Runtime.getRuntime().exec("cat /system/build.prop");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            // 查找CPU序列号
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {

                    // 查找到序列号所在行
                    if (str.indexOf("ro.build.display.id") > -1) {
                        // 提取序列号
                        strCPU = str.substring(str.indexOf("=") + 1,
                                str.length());
                        // 去空格
                        cpuAddress = strCPU.trim();
                        break;
                    }
                } else {
                    // 文件结尾
                    break;
                }
            }
            String[] strs = cpuAddress.split(" ");
            strss = strs[3];
            return strss;
        } catch (Exception ex) {

            ex.printStackTrace();
        }
        return strss;
    }

    /**
     * 小数点前后大小不一致
     *
     * @param value
     * @return
     */
    public static SpannableString changTVsize(String value) {
        SpannableString spannableString = new SpannableString(value);
        if (value.contains(".")) {
            spannableString.setSpan(new RelativeSizeSpan(0.6f), value.indexOf("."), value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }

    //用户是否登录
    public static boolean noneLogin(Context mContext) {
        String accessToken = SharePreferenceUtils.getString(mContext, "access_token", null);
        if (TextUtils.isEmpty(accessToken)) {
            Intent intent = new Intent(mContext, LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            mContext.startActivity(intent);
            return true;
        }
        return false;
    }

    /**
     * 是否登陆
     *
     * @param mContext
     * @return
     */
    public static boolean isLogin(Context mContext) {
        String accessToken = SharePreferenceUtils.getString(mContext, "access_token", null);
        if (TextUtils.isEmpty(accessToken)) return false;
        return true;
    }


    /**
     * 把中文字符串转换为十六进制Unicode编码字符串
     */
    public static String stringToUnicode(String str) {
        str = (str == null ? "" : str);
        String tmp;
        StringBuffer sb = new StringBuffer(1000);
        char c;
        int i, j;
        sb.setLength(0);
        for (i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            sb.append("\\u");
            j = (c >>> 8); //取出高8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);
            j = (c & 0xFF); //取出低8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);

        }
        return (new String(sb));
    }


    public static String decodeUnicode(String unicode) {
        try {
            StringBuffer sb = new StringBuffer();

            String[] hex = unicode.split("\\\\u");

            for (int i = 1; i < hex.length; i++) {
                int data = Integer.parseInt(hex[i], 16);
                sb.append((char) data);
            }
            return sb.toString();
        } catch (Exception e) {
            return "";
        }

    }

    /**
     * * 文件上传参数转换
     *
     * @param value 传入值
     * @return 返回值
     */
    public static RequestBody toRequestBody(String value) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
        return requestBody;
    }

    /**
     * 时间戳转换成时间
     */
    public static String stampToDate(double stamp) {
        Date date = new Date((long) (stamp * 1000L));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * 时间戳转换成时间
     */
    public static String stampToDate_2(long stamp) {
        Date date = new Date(stamp * 1000L);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    public static final int getSequence() {
        int result = getYear();
        result = 31 * result + getMonth();
        result = 31 * result + getDay();
        return result;
    }

    /**
     * 获取当前年份
     *
     * @return
     */
    public static int getYear() {
        return Calendar.getInstance().get(Calendar.YEAR);
    }

    /**
     * 获取当前月份
     *
     * @return
     */
    public static int getMonth() {
        return Calendar.getInstance().get(Calendar.MONTH) + 1;
    }

    /**
     * 获取当前日
     *
     * @return
     */
    public static int getDay() {
        return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取今天
     *
     * @return
     */
    public static String getToDay() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, 0);//-1.昨天时间 0.当前时间 1.明天时间 *以此类推
        String time = sdf.format(c.getTime());
        return time;
    }

    /**
     * 获取昨天
     *
     * @return
     */
    public static String getYesterday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, -1);//-1.昨天时间 0.当前时间 1.明天时间 *以此类推
        String time = sdf.format(c.getTime());
        return time;
    }

    //java获取当前月每天的日期
    public static List getDayListOfMonth() {
        List list = new ArrayList();
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int day = aCalendar.getActualMaximum(Calendar.DATE);
        for (int i = 1; i <= day; i++) {
            String aDate = i + "";
            list.add(aDate);
        }
        return list;
    }

    /**
     * 字符串转换成十六进制字符串
     *
     * @param str str 待转换的ASCII字符串
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
     */
    public static String HexStr(String str) {

        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;

        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            sb.append(' ');
        }
        return sb.toString().trim();
    }


    public static String getPseudo() {
        String m_szDevIDShort = "35" + "/" +//we make this look like a valid IMEI

                Build.BOARD.length() % 10 + "/" +
                Build.BRAND.length() % 10 + "/" +
                Build.CPU_ABI.length() % 10 + "/" +
                Build.DEVICE.length() % 10 + "/" +
                Build.DISPLAY.length() % 10 + "/" +
                Build.HOST.length() % 10 + "/" +
                Build.ID.length() % 10 + "/" +
                Build.MANUFACTURER.length() % 10 + "/" +
                Build.MODEL.length() % 10 + "/" +
                Build.PRODUCT.length() % 10 + "/" +
                Build.TAGS.length() % 10 + "/" +
                Build.TYPE.length() % 10 + "/" +
                Build.USER.length() % 10 + "/"; //13 digits
        return m_szDevIDShort;
    }


}
